import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'
import { Scene, Condition, Action } from '@/types/scene'

interface ImportDevice {
  id: string
  name: string
  type: string
}

interface ImportScene {
  name: string
  conditions: Condition[]
  actions: Action[]
  isActive: boolean
  devices: ImportDevice[]
}

export async function POST(request: Request) {
  try {
    const scenes = await request.json() as ImportScene[]

    if (!Array.isArray(scenes)) {
      throw new Error('无效的场景数据格式')
    }

    // 批量创建场景
    const results = await Promise.all(
      scenes.map(async (scene) => {
        try {
          const device = await prisma.scene.create({
            data: {
              name: scene.name,
              conditions: JSON.stringify(scene.conditions),
              actions: JSON.stringify(scene.actions),
              isActive: scene.isActive,
              userId: 'user_id',
              devices: {
                connect: scene.devices.map(device => ({ id: device.id }))
              }
            }
          })
          return { success: true, scene: device }
        } catch (error) {
          return { 
            success: false, 
            name: scene.name, 
            error: error instanceof Error ? error.message : '创建失败' 
          }
        }
      })
    )

    return NextResponse.json({
      success: results.some(r => r.success),
      total: scenes.length,
      imported: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
      details: results
    })
  } catch (error) {
    return NextResponse.json(
      { error: '导入场景失败' },
      { status: 500 }
    )
  }
} 